package com.guli.mall.pms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.common.constant.ProductAttrTypeEnum;
import com.guli.common.utils.CopyPageProperties;
import com.guli.common.utils.QuickSort;
import com.guli.mall.pms.entity.AttrEntity;
import com.guli.mall.pms.entity.AttrGroupEntity;
import com.guli.mall.pms.entity.vo.AttrAttrgroupRelationVo;
import com.guli.mall.pms.entity.vo.AttrTipsVo;
import com.guli.mall.pms.entity.vo.AttrVo;
import com.guli.mall.pms.service.AttrGroupService;
import com.guli.mall.pms.service.AttrService;
import com.guli.mall.serviceBase.globalException.MallException;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;

import com.guli.mall.pms.mapper.AttrAttrgroupRelationMapper;
import com.guli.mall.pms.entity.AttrAttrgroupRelationEntity;
import com.guli.mall.pms.service.AttrAttrgroupRelationService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("attrAttrgroupRelationService")
public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationMapper, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {

    @Resource
    AttrGroupService attrGroupService;

    @Resource
    AttrService attrService;

    @Override
    public PageUtils<AttrAttrgroupRelationVo> queryPage(Integer currentPage, Integer size, AttrAttrgroupRelationEntity attrAttrgroupRelationEntity) {

        Page<AttrAttrgroupRelationEntity> page = new Page<>(currentPage, size);

        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = null;

        AttrGroupEntity attrGroupEntity = null;

        if (!ObjectUtils.isEmpty(attrAttrgroupRelationEntity)) {
            wrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(attrAttrgroupRelationEntity.getAttrId())) {
                wrapper.eq("attr_id", attrAttrgroupRelationEntity.getAttrId());
            }
            if (!ObjectUtils.isEmpty(attrAttrgroupRelationEntity.getAttrGroupId())) {
                wrapper.eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId());

                attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());

            }
        }

        Page<AttrAttrgroupRelationEntity> resultPage = this.page(page, wrapper);

        // 拷贝page到vo类中
        Page<AttrAttrgroupRelationVo> voPage = CopyPageProperties.copy(resultPage, AttrAttrgroupRelationVo.class);

        // 用于判断是不是根据attrGroupId 来查询 attr-group-relation
        boolean setAttrGroupName = !ObjectUtils.isEmpty(attrGroupEntity);

        for (AttrAttrgroupRelationVo record : voPage.getRecords()) {

            // 避免空指针
            if (setAttrGroupName) {
                //
                record.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            }

            // 查询 attrId 对应的 attrName
            AttrEntity byId = attrService.getById(record.getAttrId());

            if (!ObjectUtils.isEmpty(byId)) {

                record.setAttrName(byId.getAttrName());
            } else {
                record.setAttrName("找到不到该属性");
            }
        }

        Comparator<AttrAttrgroupRelationVo> comparator = (a1, a2) -> {
            return a1.getAttrSort() - a2.getAttrSort();
        };

        QuickSort.sort(voPage.getRecords(), comparator);


        return new PageUtils<>(voPage);
    }

    @Override
    public AttrAttrgroupRelationEntity getAttrGroupRelationByAttrId(Long attrId) {

        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("attr_id", attrId);

        return this.getOne(wrapper, false);
    }

    @Override
    public void updateByAttrId(AttrAttrgroupRelationEntity relation) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("attr_id", relation.getAttrId());

        this.update(relation, wrapper);
    }

    @Override
    public PageUtils<AttrTipsVo> getAvailableBindingAttr(AttrAttrgroupRelationVo attrAttrgroupRelationVo, Integer currentPage, Integer size) {
        /**
         * 查询该attrGroupId所属的分类
         * */
        AttrGroupEntity basicGroup = attrGroupService.getById(attrAttrgroupRelationVo.getAttrGroupId());

        if (ObjectUtils.isEmpty(basicGroup) && ObjectUtils.isEmpty(basicGroup.getCatelogId())) {
            throw new MallException("该attrGroupId不存在或者没有设置所属分类categoryId");
        }
        /**
         * 该attr-group有所属的分类 category，
         * 查询该category下的所有属性分组
         * */
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();

        attrGroupEntityQueryWrapper.eq("catelog_id", basicGroup.getCatelogId());

        List<AttrGroupEntity> attrGroupList = attrGroupService.list(attrGroupEntityQueryWrapper);

        // 这里应该不会被触发
        if (CollectionUtils.isEmpty(attrGroupList)) {
            throw new MallException("catelogId = " + basicGroup.getCatelogId() + "下不存在对应的属性分组");
        }

        /**
         * 使用查询的属性分组集合 attr-group-list 去 attr-group-relation 中查询其对应的所有属性Id attrId
         * （1）先把attrGroupList 中的attrGroupId取出，放到集合 attrGroupIdList 中
         * */
        List<Long> attrGroupIdList = attrGroupList.stream().map(group -> {

            return group.getAttrGroupId();

        }).collect(Collectors.toList());

        // 该catelogId下已经被attrGroup绑定了的属性
        List<AttrAttrgroupRelationEntity> boundAttrRelation = null;

        if (CollectionUtils.isEmpty(attrGroupIdList)) {
            log.warn("该catelogId分类下的所有attrGroupList没有一个有对应的attrId属性");
        } else {
            /**
             * （2）获取attrGroupId对应的attrId
             * */
            QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();

            relationWrapper.in("attr_group_id", attrGroupIdList);

            boundAttrRelation = this.list(relationWrapper);
        }

        /**
         * 只查询当前分类categoryId下的所有的属性
         * */
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();

        attrEntityQueryWrapper.eq("catelog_id", basicGroup.getCatelogId());

        // 只能关联基本属性，不关联销售属性
        attrEntityQueryWrapper.eq("attr_type", ProductAttrTypeEnum.BASIC_ATTRIBUTE.getValue());

        /**
         * 进行其他条件查询
         * */
        if (!ObjectUtils.isEmpty(attrAttrgroupRelationVo.getAttrId())) {
            // 根据attrId进行查询属性
            attrEntityQueryWrapper.eq("attr_id", attrAttrgroupRelationVo.getAttrId());
        }

        if (!StringUtils.isEmpty(attrAttrgroupRelationVo.getAttrName())) {
            // 根据属性名来查询属性
            attrEntityQueryWrapper.like("attr_name", attrAttrgroupRelationVo.getAttrName());
        }

        Page<AttrEntity> page = attrService.page(new Page<AttrEntity>(currentPage, size), attrEntityQueryWrapper);

        // 拷贝到有提示信息的vo中
        Page<AttrTipsVo> pageVo = CopyPageProperties.copy(page, AttrTipsVo.class);

        /**
         * categoryId下，所有attrGroup都没有绑定attr，所以可以提前返回
         * */
        if (ObjectUtils.isEmpty(boundAttrRelation)) {
            return new PageUtils<>(pageVo);
        }

        /**
         * 将已经绑定了的属性放到map中
         * */
        Map<Long, AttrAttrgroupRelationEntity> map = new HashMap<>();

        for (AttrAttrgroupRelationEntity entity : boundAttrRelation) {
            map.put(entity.getAttrId(), entity);
        }

        List<AttrTipsVo> records = pageVo.getRecords();


        for (AttrTipsVo record : records) {

            /**
             * 如果attr-group 在attr-group-relation 表中已经包含了该属性，就移除该属性
             */
            AttrAttrgroupRelationEntity relation = map.get(record.getAttrId());

            if (!ObjectUtils.isEmpty(relation)) {
                //records.remove(i);
                //i--;
                AttrGroupEntity groupEntity = attrGroupService.getById(relation.getAttrGroupId());
                record.setMessage("已绑定" + groupEntity.getAttrGroupName());
                record.setBindable(false);
            }
        }
        return new PageUtils<>(pageVo);
    }

    @Override
    public List<Long> getAttrIdListByAttrGroupIdList(Long attrGroupId) {

        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("attr_group_id", attrGroupId);

        List<AttrAttrgroupRelationEntity> list = this.list(wrapper);

        // 排序
        QuickSort.sort(list, (r1, r2) -> {
            return r1.getAttrSort() - r2.getAttrSort();
        });

        // 从 attr-group-relation list 中抽取出 attrId 作为 list返回
        return list.stream().map(relation->{
            return relation.getAttrId();
        }).collect(Collectors.toList());
    }

}